from Crypto.Random import get_random_bytes
from Crypto.Cipher import AES
from Crypto.Hash import SHA256
from Crypto.PublicKey import ECC
from Crypto.Signature import DSS
from Crypto.Util.Padding import pad, unpad

data = b'1233211234567'

# SHA256
print('SHA256')
print('data = ',data)
h = SHA256.new(data)
print('hash(data) = ', h.hexdigest())

# AES
print('AES')
key = get_random_bytes(16)  # 随机生成key用以生成密钥
encryptor = AES.new(key, AES.MODE_ECB)
e_data = encryptor.encrypt(pad(data, 16))
print("password:", data)
print("encrypted password:", e_data)
print("key:", key)
decrypter = AES.new(key, AES.MODE_ECB)
d_data = decrypter.decrypt(e_data)
print("decrypted password:", unpad(d_data, 16))

# ECDSA
print('ECDSA')
private_key = ECC.generate(curve='P-256')
public_key = private_key.public_key()
h = SHA256.new(data)
signer = DSS.new(private_key, 'fips-186-3')
signature = signer.sign(h)
print('signature: ', signature)
received_data1 = data
received_data2 = b'1233221234567'  # 和原数据不同
h1 = SHA256.new(received_data1)
verifier = DSS.new(public_key, 'fips-186-3')
try:
    verifier.verify(h1, signature)
    print("The message is authentic.")
except ValueError:
    print("The message is not authentic.")

h2 = SHA256.new(received_data2)
verifier = DSS.new(public_key, 'fips-186-3')
try:
    verifier.verify(h2, signature)
    print("The message is authentic.")
except ValueError:
    print("The message is not authentic.")
